# Maintainer: George Rawlinson <grawlinson@archlinux.org>
# Contributor: Kenneth Endfinger <kaendfinger@gmail.com>

pkgname=buildkit
pkgver=0.12.2
pkgrel=1
pkgdesc='A toolkit for converting source code to build artifacts in a repeatable manner'
arch=('loong64' 'x86_64')
url='https://github.com/moby/buildkit'
license=('Apache')
depends=('runc' 'containerd')
makedepends=('git' 'go')
options=('!lto')
_commit='567a99433ca23402d5e9b9f9124005d2e59b8861'
source=("$pkgname::git+$url.git#commit=$_commit"
0001-add-loongarch64-support.patch)
b2sums=('SKIP'
        '633f1e8e9e66c38f3a21a6c3af14721efd6a2cc6c0201e8492d333a86461a5783eec2c144edfe1ef17ee8385fa29588f30e88d26cf49ce8b477480be3e5459be')

pkgver() {
  cd "$pkgname"

  # ignore docker tags
  git describe --tags --exclude 'dockerfile*' | sed 's/^v//'
}

prepare() {
  cd "$pkgname"

  # fix paths in systemd unit files
  sed -i 's:/usr/local:/usr:' \
    examples/systemd/{system,user}/*.service
  patch -p1 -i $srcdir/0001-add-loongarch64-support.patch

  # create directory for build output
  mkdir build

  # download dependencies
  export GOPATH="${srcdir}"
  go mod download
}

build() {
  cd "$pkgname"

  # set Go flags
  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export GOPATH="${srcdir}"

  go mod edit -replace=golang.org/x/sys=github.com/golang/sys@v0.13.0
  go mod edit -replace=go.etcd.io/bbolt=go.etcd.io/bbolt@v1.3.7-0.20221114114133-eedea6cb26ef
  go mod tidy

  local package='github.com/moby/buildkit'

  go build -v \
    -buildmode=pie \
    -mod=readonly \
    -modcacherw \
    -ldflags "-compressdwarf=false \
    -linkmode external \
    -extldflags ${LDFLAGS} \
    -X ${package}/version.Version=$pkgver \
    -X ${package}/version.Revision=$_commit" \
    -o build \
    ./cmd/...
}

package() {
  cd "$pkgname"

  # binaries
  install -vDm755 -t "$pkgdir/usr/bin" build/*

  # documentation
  install -vDm644 -t "$pkgdir/usr/share/doc/$pkgname" README.md
  cp -vrt "$pkgdir/usr/share/doc/$pkgname" docs

  # systemd integration
  install -vDm644 -t "$pkgdir/usr/lib/systemd/system" examples/systemd/system/*
  install -vDm644 -t "$pkgdir/usr/lib/systemd/user" examples/systemd/user/*
}
